/*
 * Copyright(c) 2018-? the original author[Wien(luweien@aliyun.com)] or authors.
 *
 */
package org.doll.it.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.doll.it.base.constant.Consts;
import org.doll.it.web.session.DollUserUtils;
import org.doll.it.web.session.SessionUserVO;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import lombok.extern.slf4j.Slf4j;

/**
 * API拦截器
 * 
 * @author Wien(luweien@aliyun.com)
 *
 */
@Slf4j
public class ApiInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		log.debug("---ApiInterceptor-preHandle: " + handler);

		// 设置当前session用户
		HttpSession session = request.getSession();
		SessionUserVO sessionUserVO = (SessionUserVO) session.getAttribute(Consts.SESSION_USER_NAME);
		if (sessionUserVO == null) {
			DollUserUtils.setSessionId(session.getId());
		} else {
			sessionUserVO.setSessionId(session.getId());
			DollUserUtils.setCurrUser(sessionUserVO);
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		log.debug("---ApiInterceptor-postHandle: " + handler);

		// 清理
		DollUserUtils.destroyCurrUser();
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		log.debug("---ApiInterceptor-afterCompletion: " + handler);

		// 清理
		DollUserUtils.destroyCurrUser();
	}

	//	private void responseResult(HttpServletResponse response, Object result)
	//			throws JsonProcessingException, IOException {
	//		response.setCharacterEncoding(Consts.UTF_8);
	//		response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE);
	//		response.setStatus(CodeEnum.OK.getCode());
	//
	//		ObjectMapper mapper = new ObjectMapper();
	//		response.getWriter().write(mapper.writeValueAsString(result));
	//	}
}
